// pages/user/shop-ask/shop-ask.js
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
import Dialog from '../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'
let app = getApp();
let bmap = require('../../../utils/bmap-wx.min.js');
const areaJson = require('../../../utils/areaJson/area.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showNumber:false,
    sessionKey:'',
    user: '',
    btnText: '提交申请',
    isDis: false,
    isPartner: false,//合伙人弹框
    centerList: [],
    centerIndex: '',
    partnerColumns: [],//合伙人数据
    areaShow: false,//省市区弹框
    areaList: areaJson.area,//省市区数据，在area.josn获取
    code: '',//推荐人
    upname: '',//推荐人名字
    upcentreId: '',//推荐商户
    lng: '',
    lat: '',

    name: '',
    mobile: '',
    belongTo: '请选择合伙人',
    province: '',
    city: '',
    area: '',
    address: '',//详细地址
    xiaoQu: '',//小区
    remark: '',
    store:'',//门头照
    tHouseNum:'',//门牌号
  },

  //提交
  onSubmit() {
    let _this = this;
    if(_this.data.store == ''){
      Toast('请上传门头照'); return;
    }else if (_this.data.name == '') {
      Toast('请填写姓名'); return;
    } else if (_this.data.mobile == '' || !(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(_this.data.mobile))) {
      Toast('请填写正确的手机号码'); return;
    }else if (_this.data.area == '') {
      Toast('请选择所在地区'); return;
    } else if (_this.data.xiaoQu == '') {
      Toast('请填写分店名称'); return;
    }else if(_this.data.address == ''){
      Toast('请填写详细地址'); return;
    }else if(_this.data.tShopname == ''){
      Toast('请填写门牌号'); return;
    }

    if (_this.data.user.id == null)
      _this.toDoLogin();
    else
      _this.toDoSubmit();
  },

  //申请
  toDoSubmit() {
    let _this = this;
    this.data.user = app.getUser();
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/shop/reg',
      data: {
        id: _this.data.user.id,
        realname: _this.data.name,
        mobile: _this.data.mobile,
        tProvince: _this.data.province,
        tCity: _this.data.city,
        tArea: _this.data.area,
        tXiaoqu: _this.data.xiaoQu,
        tAddress: _this.data.address,
        tHouseNum:_this.data.tHouseNum,
        tShopname: _this.data.user.tShopname,
        isteamDesc: '',
        invitaCode: _this.data.code,
        tLng: _this.data.lng,
        tLat: _this.data.lat,
        tZuobiao: _this.data.lng + ',' + _this.data.lat,
        // centreId: _this.data.centerList[_this.data.centerIndex].centreId
        centreId: app.globalData.loginCentreId,
        store:_this.data.store
      }
    }).then(res => {
      if (res.data.data > 0) {
        Toast.success("提交成功")
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }, 1500)
      } else {
        Toast.fail('提交申请失败')
      }
    })
  },

  //登录
  toDoLogin() {
    let _this = this;
    wx.login({
      success: function (res) {
        var code = res.code;
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              app.requestUrl({
                method: 'POST',
                url: '/wxapi/app/login',
                data: {
                  code: code,
                  centreId: app.globalData.loginCentreId,
                  flag: 1,
                },
                load: 1,
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
              }).then((data) => {
                if (data.data.success)
                  _this.wxUserInfo(res, data.data.data);
              });
            }
          })
        }
      }
    })
  },
  //上传头像
  avatarAfterRead(event) {
    let _this = this;
    const { file } = event.detail;
    wx.uploadFile({
      url: app.globalData.deployUrl + '/platform/config/upload', // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        let data = JSON.parse(res.data)
        _this.setData({
          'store': data.key,
        })
      }
    });
  },
  // 详细地址
  call_map:function(){
    let _this = this;
    wx.getLocation({////获取当前位置信息
      type: 'wgs84',
      //获取位置成功
      success: function (res) {
        console.log(res)  //获取的的当前位置的详细信息
        wx.chooseLocation({////选择位置
          success: function (res) {
            _this.setData({
              address: res.name,
              lat: res.latitude,
              lng: res.longitude,
            });
          }
        })
      },
      //获取位置失败
      fail: function (err) {
        console.log("拒绝访问地址权限")
      },
      //接口调用结束的回调函数（调用成功、失败都会执行）
      complete: function (info) {
        console.log("完成")
      },
    })
  },
  //得到用户信息
  wxUserInfo(res, encryptInfo) {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/app/sendXcxUnionId',
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        sessionKey: encryptInfo
      },
      load: 1,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
    }).then((data) => {
      //4.解密成功后 获取自己服务器返回的结果
      if (data.data.success) {

        let info = data.data.data;
        wx.setStorageSync('userInfo', JSON.stringify(info));//保存用户信息
        wx.setStorageSync('authToken', data.data.authToken);//保存身份验证
        if(info.mobile == ''){
          _this.setData({
            showNumber:true,
            sessionKey: encryptInfo,
          });
        }else{
          _this.toDoSubmit();
        };
      }
    })
  },
  getPhoneNumber(e){
    let _this = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/getEncryptedUserInfo',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: _this.data.sessionKey,
        },
        load: 0,
      }).then((data)=>{
        if (data.data.success){
          _this.toDoSubmit();
        }
          
      });
    }
    
  },

  //获取合伙人数据
  getCenterList() {
    let _this = this;

    app.requestUrl({
      method: 'GET',
      url: '/wxapi/center/list',
      data: {},
      load: 1
    }).then(res => {
      res.data.data.filter(item => {
        _this.data.partnerColumns.push({ name: item.name, centreId: item.centreId });
      })
      _this.setData({
        centerList: res.data.data,
        partnerColumns: _this.data.partnerColumns
      })
    })
  },

  //合伙人确认
  partnerConfirm(event) {
    let _this = this;
    _this.setData({
      centerIndex: event.detail.index,
      belongTo: _this.data.partnerColumns[event.detail.index].name
    })
    _this.isPartnerMonitor();
  },
  isPartnerMonitor() {
    let _this = this;
    if (_this.data.upcentreId) return;
    _this.setData({
      isPartner: !_this.data.isPartner
    })
  },

  //获取当前位置
  // getPosition() {
  //   let _this = this;

  //   if (_this.data.area) return;

  //   let BMap = new bmap.BMapWX({
  //     ak: app.globalData.AK,

  //   });
  //   let fail = function (data) {
  //     console.log(data);
  //     _this.inspectJurisdiction();
  //   };
  //   let success = function (data) {
  //     // 返回数据内，已经包含经纬度
  //     console.log(data);
  //     let result = data.originalData.result;
  //     _this.setData({
  //       province: result.addressComponent.province,
  //       city: result.addressComponent.city,
  //       area: result.addressComponent.district,
  //       address: result.formatted_address,
  //       xiaoQu: result.sematic_description,
  //       lng: result.location.lng,
  //       lat: result.location.lat,
  //     })
  //   };

  //   // 发起regeocoding检索请求
  //   BMap.regeocoding({
  //     fail: fail,
  //     success: success
  //   });
  // },

  //检查是否允许定位权限
  inspectJurisdiction() {
    //判断是否获得了用户地理位置授权
    wx.getSetting({
      success: (res) => {
        console.log(res)
        if (!res.authSetting['scope.userLocation'])
          Dialog.confirm({
            title: '温馨提示',
            message: '获取定位失败，请前往设置打开定位授权',
            confirmButtonOpenType: 'openSetting'
          }).then(() => {
            wx.openSetting({
              success: (res) => {

              }
            })
          })
      }
    })
  },

  //省市区确定
  areaConfirm(event) {
    let _this = this;
    _this.setData({
      province: event.detail.values[0].name,
      city: event.detail.values[1].name,
      area: event.detail.values[2].name,
    })
    _this.areaMonitor();
  },
  //省市区弹框
  areaMonitor() {
    let _this = this;
    _this.setData({
      areaShow: !_this.data.areaShow
    })
  },

  nameBlur(event) {
    this.setData({ name: event.detail.value })
  },
  mobileBlur(event) {
    this.setData({ mobile: event.detail.value })
  },
  xiaoQuChange(event) {
    this.setData({ xiaoQu: event.detail })
  },
  addressBlur(event) {
    this.setData({ address: event.detail.value })
  },
  remarkBlur(event) {
    this.setData({ remark: event.detail.value })
  },
  tHouseNumBlur(event){
    this.setData({ tHouseNum: event.detail.value })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    console.log(event)
    let scene = event.scene;
    if (scene) {//根据小程序码进入
      let tt = scene.split('-');
      let obj = {};
      tt.forEach(item => {
        obj[item.split('!')[0]] = item.split('!')[1];
      })
      console.log(obj)
      this.setData({
        code: obj.cd || '',
        upcentreId: obj.cid || '',
      })
    } else {
      this.setData({
        code: event.code || '',
        upname: event.upname || '',
        upcentreId: event.upcentreid || '',
      })
    }

    this.setData({
      user: app.getUser(),
      name: app.getUser().nickname,
      mobile: app.getUser().mobile,
      province: app.getUser().tProvince,
      city: app.getUser().tCity,
      area: app.getUser().tArea,
      xiaoQu: app.getUser().tXiaoqu,
      address: app.getUser().tAddress,
      remark: app.getUser().remark,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getPosition();
    this.getCenterList();
    if (this.data.user.isteam === 4) { //申请中，审核通过未开通
      Toast('申请已提交，请等待审核');
      this.setData({
        isDis: true,
        btnText: '审核中'
      })
      return;
    } else if (this.data.user.isteam === 3) { //已经是门店
      Toast('您已经是门店');
      this.setData({
        isDis: true,
        btnText: '门店'
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }, 1500)
      return;
    }
    setTimeout(() => {
      if (this.data.upcentreId) {//设置所选商户
        this.data.partnerColumns.forEach((item, index) => {
          if (this.data.upcentreId == item.centreId) {
            this.setData({
              belongTo: item.name,
              centerIndex: index,
            })
          }
        })
      }
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})